package com.arlen.general.util;

import com.arlen.general.exceptionHandle.WxCustomException;
import com.arlen.general.mapper.OssMapper;
import com.arlen.general.pojo.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

//微信消息接收于响应的工具类

public class WxMessageUtil {
    private static final Logger logger = LoggerFactory.getLogger(WxMessageUtil.class);

    /**
     * @Description 解析用户发送到公众号的消息 dom4j
     * @Date 2021/4/17
     * @return map
     **/
    public static Map<String, String> analysisMessage(HttpServletRequest request) throws WxCustomException {
        Map<String, String> messageMap = new HashMap<>();
        ServletInputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Optional<ServletInputStream> optional = Optional.ofNullable(inputStream);
        if (!optional.isPresent()) {
            logger.warn("request inputStream is null !");
            throw new IllegalStateException();
        }
        //使用dom4j 解析
        SAXReader reader = new SAXReader();
        try {
            //解析xml 获取文档
            Document document = reader.read(inputStream);
            //获取文档中的根节点
            Element rootElement = document.getRootElement();
            //获取根节点下的全部字节点
            List<Element> elements = rootElement.elements();
            Iterator<Element> iterator = elements.iterator();
            while (iterator.hasNext()) {
                Element element = iterator.next();
                messageMap.put(element.getName(), element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return messageMap;
    }


    private static final PropertiesUtils propertiesUtils = new PropertiesUtils();

    public static final String secret = propertiesUtils.getProperValue("backdoor.order");;


    public static <T extends BaseMessage> T responseMessage(Map<String, String> messageMap) throws Exception {
        //创建发送请求的类
        HttpRequest request = HttpRequest.getHttpRequest();

        String type = messageMap.get("MsgType");
        BaseMessage message = null;
        switch (type) {
            case "text":
                message = new TextMessage(messageMap);
                String content = messageMap.get("Content");
                if (content.equals(secret)){
                    message = secretResponse(messageMap);

                }else {
                QiingYunke yunke = new QiingYunke();
                yunke.setMes(content);
                String responseMas = request.sendGet(null, yunke);
                if (StringUtils.isNoneBlank(responseMas)){
                    ((TextMessage) message).setContent("analysis fail !");
                }
                ((TextMessage) message).setContent(responseMas);
                }
                break;
            case "image":

                break;
            case "voice":

                break;
            case "video":

                break;
            case "music":

                break;
            case "news":

                break;
            default:
               break;
        }
        return (T)message;
    }
    @Autowired
    private static OssMapper ossMapper;
    //回复秘密的图文消息
    private static NewsMessage secretResponse(Map<String, String> messageMap) {
        NewsMessage newsMessage = new NewsMessage(messageMap);
        String aliyunPrefix = propertiesUtils.getProperValue("aliyun.url");
        Po_OSs po_oSs = ossMapper.selectById(1);
        aliyunPrefix = aliyunPrefix+ po_oSs.getImage();
        return newsMessage;
    }





   /* 设置返回消息方法
    private static <T> T answer(T t) {
        try {
            Object o = t.getClass().newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        todo :或许这样更加灵活
        return t;
    }*/

}
